package com.leyou.order.interceptor;

import com.leyou.common.utils.UserHolder;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String userId = request.getHeader("user_info");
        if (StringUtils.isBlank(userId)){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }

        UserHolder.setUser(Long.valueOf(userId));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserHolder.remove();
    }
}
